<template>
  <div>
    <div class="top">
      <span class="demonstration">选择商品分类：</span>
      <el-cascader
        @change="getAttributeList"
        v-model="value"
        :options="list"
        :props="{
          label: 'cat_name',
          value: 'cat_id',
        }"
      ></el-cascader>
    </div>
    <div class="content">
      <el-tabs v-model="activeName" @tab-click="getAttributeList">
        <el-tab-pane
          :key="key"
          v-for="(item, key) in type"
          :label="item.type + item.title"
          :name="key"
        >
          <el-button
            :disabled="!catId"
            @click="
              model = {};
              $refs.df.show();
            "
            type="primary"
            size="small"
          >
            添加{{ item.title }}
          </el-button>
          <p></p>
          <Table
            rowKey="attr_id"
            :loading="loading"
            :cols="cols"
            :data="attributeList"
          >
            <template v-slot:expand="{ row }">
              <el-tag
                @close="deleteTag(row, index)"
                class="tag"
                v-for="(item, index) in row.tags"
                :key="index"
                closable
                :disable-transitions="false"
                >{{ item }}</el-tag
              >
              <el-input
                class="input-new-tag"
                v-if="row.visible"
                v-model="row.value"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                size="small"
                @click="
                  row.visible = true
                "
                >+ New Tag</el-button
              >
            </template>
          </Table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <DF
      @confirm="confirm"
      :title="'添加' + title"
      :value="model"
      :opts="opts"
      ref="df"
    />
  </div>
</template>

<script>
import {
  getCategories,
  getAttributes,
  updateAttribute,
  addAtrribute,
} from "@/api/goods";
export default {
  name: "Params",
  data() {
    return {
      /**
       * 数据模型
       */
      model: {},
      /**
       * loading
       */
      loading: false,
      /**
       * 类型
       */
      type: {
        many: {
          type: "动态",
          title: "参数",
        },
        only: {
          type: "静态",
          title: "属性",
        },
      },
      /**
       * 激活的名称
       */
      activeName: "many",
      /**
       * 选中的值
       */
      value: [],
      /**
       * 数据列表
       */
      list: [],
      /**
       * 属性列表
       */
      attributeList: [],
    };
  },
  methods: {
    /**
     * 提交
     */
    async confirm(model) {
      const df = this.$refs.df;
      try {
        df.start();
        await addAtrribute(this.catId, { ...model, attr_sel: this.activeName });
        this.$m.success("属性添加成功");
        this.getAttributeList();
        df.hide();
      } catch (error) {}
      df.stop();
    },
    /**
     * 删除标签
     */
    async deleteTag(row, index) {
      try {
        const { attr_id, attr_sel, attr_name } = row;
        row.tags.splice(index, 1);
        const attr_vals = row.tags.join(",");
        await updateAttribute(this.catId, attr_id, {
          attr_vals,
          attr_name,
          attr_sel,
        });
        this.$m.success("参数修改成功");
        this.getCategoryList();
      } catch (error) {}
    },
    /**
     * 处理输入框内容
     */
    async handleInputConfirm(row) {
      const value = row.value?.trim();
      const { attr_name, attr_sel } = row;
      try {
        if (!value) return;
        this.loading = true;
        const attr_vals = [...row.tags, value].join(" ");
        await updateAttribute(this.catId, row.attr_id, {
          attr_vals,
          attr_name,
          attr_sel,
        });
        row.value = "";
        row.tags.push(value);
        this.$m.success("参数修改成功");
        this.getCategoryList();
      } catch (error) {
      } finally {
        row.visible = false;
        this.loading = false;
      }
    },
    /**
     *  获取属性
     */
    async getAttributeList() {
      try {
        if (!this.catId) return;
        this.loading = true;
        this.attributeList = await getAttributes(this.catId, this.activeName);
        this.attributeList.forEach((item) => {
          this.$set(item, "visible", false);
          this.$set(item, "value", "");
          item.tags = item.attr_vals?.split(",")?.filter((c) => c) || [];
        });
      } catch (error) {}
      this.loading = false;
    },
    /**
     * 获取分类列表
     */
    async getCategoryList() {
      try {
        this.list = await getCategories();
      } catch (error) {}
    },
  },
  created() {
    this.getCategoryList();
  },
  computed: {
    /**
     * 标题
     */
    title() {
      const item = this.type[this.activeName];
      return item.type + item.title;
    },
    /**
     * 表单选项
     */
    opts() {
      return {
        attr_name: {
          title: this.title,
          required: true,
          max: 20,
        },
      };
    },

    /**
     *  分类ID
     */
    catId() {
      return this.value.length > 2 && this.value[2];
    },
    /**
     * 列
     */
    cols() {
      return [
        {
          title: "",
          type: "expand",
          slot: "expand",
        },
        {
          title: "#",
          type: "index",
        },
        {
          title: this.type[this.activeName]?.title + "名称",
          name: "attr_name",
        },
        {
          title: "操作",
          align: "center",
          width: 200,
          slot: "action",
        },
      ];
    },
  },
};
</script>

<style lang='less' scoped>
.tag {
  margin-left: 10px;
}
.input-new-tag {
  width: 100px;
}
</style>
